package com.sat.user.controller;

import com.sat.common.entity.BCrypt;
import com.sat.common.entity.Result;
import com.sat.order.config.OrderFeign;
import com.sat.user.model.User;
import com.sat.user.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderFeign orderFeign;

    /**
     * 账号密码登录
     *
     * @param username 账号
     * @param password 密码
     * @return
     */
    @RequestMapping("/login")
    public Result login(String username, String password) {
        // 明文
        // 根据账号和密码查询
        // 数据库的账号和密码是密文的
        // 根据账号查询用户
        // 获取用户的密码 （密文）
        User loginUser = userService.getById(username);
        if (loginUser == null) {
            Map<String, String> map = new HashMap<>();
            map.put("username", username);
            map.put("password", password);
            return Result.error("账号不存在");
        }
        String password1 = loginUser.getPassword();


        boolean checkpw = BCrypt.checkpw(password, password1);
        if (checkpw) {
            //将cookie中的数据保存到购物车
            orderFeign.cookieToRedis(username);
            return Result.OK("登录成功");
        } else {
            Map<String, String> map = new HashMap<>();
            map.put("username", username);
            map.put("password", password);
            return  Result.error("账号或者密码错误");
        }

    }

    @GetMapping("{id}")
    public Result getById(@PathVariable String id){
        User user = userService.getById(id);
        return Result.OK("查询成功",user);
    }
}
